<?php

/*
Aurus CMS - free OOP CMS
Copyright (C) 2010  Nestor Yanchuk

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
if (!defined('ROOT'))
die();

class Module_news implements Module {

	public function run() {
		if (isset($_GET['do']) && $_GET['do'] == 'addnews') {
			$this->addNews();
		} elseif (isset($_GET['shownews'])) {
			$this->showFull();
		} elseif (isset($_GET['edit']) || isset($_GET['delete'])) {
			$this->edit();
		} elseif (isset($_GET['fix']) && $_GET['fix'] == 'news') {
			$this->fix();
		} else { //Get last news
			$this->showShort();
		}
	}

	protected function fix() {
		if (Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'fixNews')) {
			$newsNfo = Mysql::getInstance()->select('news', 'is_fixed', 'id=' . toInt($_GET['id']));

			if (boolean($newsNfo[0]['is_fixed'])) {
				Mysql::getInstance()->update('news', array('is_fixed' => '0'), 'id=' . toInt($_GET['id']));
				Aurus::getInstance()->setError(__('Фіксацію знято'));
			} else {
				Mysql::getInstance()->update('news', array('is_fixed' => '1'), 'id=' . toInt($_GET['id']));
				Aurus::getInstance()->setError(__('Новину зафіксовано'));
			}
		} else {
			Aurus::getInstance()->setError(__('Ви не можете фіксувати новини'));
		}
	}

	public function onActivate() {
		$sql[] = "CREATE TABLE IF NOT EXISTS `" . PREFIX . "_news` (
  `id` int(255) NOT NULL auto_increment,
  `title` varchar(50) NOT NULL,
  `sstory` mediumtext NOT NULL,
  `fstory` mediumtext NOT NULL,
  `author` int(11) NOT NULL,
  `category` int(10) NOT NULL,
  `comm_num` int(11) NOT NULL,
  `is_moderated` int(2) NOT NULL,
  `rating` int(11) NOT NULL,
  `is_fixed` int(11) NOT NULL,
  `time_add` int(11) NOT NULL,
  UNIQUE KEY `id` (`id`),
  UNIQUE KEY `id_2` (`id`),
  FULLTEXT KEY `sstory` (`sstory`,`fstory`,`title`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;";


		$sql[] = "CREATE TABLE IF NOT EXISTS `" . PREFIX . "_news_comments` (
  `com_id` int(11) NOT NULL auto_increment,
  `news_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `user_name` varchar(15) NOT NULL,
  `time` int(11) NOT NULL,
  `email` varchar(15) NOT NULL,
  `text` mediumtext NOT NULL,
  `is_logged` int(11) NOT NULL,
  PRIMARY KEY  (`com_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
";
		$sql[] = "CREATE TABLE IF NOT EXISTS `" . PREFIX . "_categories` (
  `catid` int(11) NOT NULL auto_increment,
  `cat_name` varchar(255) NOT NULL,
  `parent` int(11) NOT NULL,
  PRIMARY KEY  (`catid`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;";


		foreach ($sql as $s) {
			Mysql::getInstance()->query($s);
		}
	}

	public function onDeactivate() {

	}

	public function runAjax() {
		if (!empty($_POST['del-com-id'])) {
			$_POST['del-com-id'] = (int) $_POST['del-com-id'];
			$com = Mysql::getInstance()->getarray("SELECT * FROM `" . PREFIX . "_news_comments` WHERE com_id='{$_POST['del-com-id']}'");
			if (Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'commDeleteSelf') && $com['user_id'] == Users::getInstance()->getLoggedUsersData('uid')) {
				$this->deleteComment($com['news_id'], $com['com_id']);
				echo '<strong>' . __('Коментар видалено') . '</strong>';
			} elseif (Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'commDeleteAll')) {
				$this->deleteComment($com['news_id'], $com['com_id']);
				echo '<strong>' . __('Коментар видалено') . '</strong>';
			}
		} elseif (!empty($_POST['edit-com-id'])) {
			if ((int) $_POST['edit-com-id']) {
				echo $this->editComment((int) $_POST['edit-com-id'], true);
			}
		} elseif (!empty($_POST['action']) && (int) $_GET['action'] == 1 && Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'editNews')) {
			$_GET['eid'] = $_GET['news'];
			Aurus::getInstance()->addContent(Aurus::getInstance()->getClientJs());
		} elseif (isset($_POST['prev']) && $_POST['prev'] == 1) {
			echo Parser::getInstance()->parse($_POST['text']);
		} elseif (isset($_POST['com_ajax']) && $_POST['com_ajax'] == 'yes' && isset($_POST['ajax_confirm']) && $_POST['ajax_confirm'] == 'yes') {
			echo $this->ajaxConfirm($_POST['text'], $_POST['com_id'], Users::getInstance()->getLoggedUsersData('uid'));
		} elseif (isset($_POST['cansel_edit']) && $_POST['cansel_edit'] == 'yes') {
			$c = Mysql::getInstance()->select('news_comments', '*', 'com_id=' . $_POST['com_id'], 1);
			echo $c[0]['text'];
		} elseif (isset($_GET['upload_file']) && $_GET['upload_file'] == 'true') {
			Upload::uploadFile('file', 'news');
			echo $this->getUploaded();
		} elseif (false) {

		}
	}

	private function getUploaded() {
		$upl = Upload::getUploadFiles('news');
		$ret = '<ul class="">';
		foreach ($upl as $file) {
			$ret .= '<li>' . $file['name'] . '</li>';
		}
		$ret .= '</ul>';
		return $ret;
	}

	private function editComment($comId, $ajax = false) {
		$ret = '';
		$comInfo = Mysql::getInstance()->select('news_comments', '*', "com_id='{$comId}'");
		$comInfo = $comInfo[0];
		if ((Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'commDeleteSelf') && $comInfo['user_id'] == Users::getInstance()->getLoggedUsersData('uid')) or Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'commDeleteAll')) {
			if ($ajax) {
				$ret = '<div id="com_edit_' . $comId . '_prev" />';
				$ret .= str_replace('{THEME}', LINK_ROOT . 'templates/' . Aurus::getInstance()->getTemplateToLoad(), Aurus::getInstance()->getEditor());
				Aurus::getInstance()->addJs('BB.init();');
				$ret .= '<textarea style="width:550px;height:200px;" id="com_edit_' . $comId . '">' . Parser::getInstance()->unParseBB(stripslashes($comInfo['text'])) . '</textarea><br />';
				$ret .= '<input value="' . __('Зберегти') . '" type="button" onclick="' . "au_ajax('news',{'text': $('#com_edit_{$comId}').val() ,'ajax_confirm':'yes','com_ajax':'yes','com_id': {$comId}},'com-{$comId}',1,1)" . '"  /> | ';
				$ret .= '<input value="' . __('Переглянути') . '" type="button" onclick="' . "au_ajax('news',{prev:1,text: $('#com_edit_{$comId}').val()} ,'com_edit_{$comId}_prev','1',0)" . '"  /> | ';
				$ret .= '<input value="' . __('Відмінити') . '" type="button" onclick="' . "au_ajax('news',{'com_id': {$comId},'cansel_edit':'yes'},'com-{$comId}',1,1)" . '"  />';
			} else {
				$com = Mysql::getInstance()->getarray("SELECT * FROM `" . PREFIX . "_news_comments` WHERE com_id='{$comId}'");
				if ((Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'commDeleteSelf') && $com['user_id'] == Users::getInstance()->getLoggedUsersData('uid')) or Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'commDeleteAll')) {
					if (isset($_POST['message'])) {
						$err = false;
						if (strlen($_POST['message']) < (int) Config::get('commMinLenght', 'news')) {
							$err = true;
							Aurus::getInstance()->setError(format(__('Коментар занадто короткий, збільшіть його хоча б до {%1%} символів'), Config::get('commMinLenght', 'news')));
						}
						$parsed = Parser::getInstance()->parse($_POST['message']);
						if (!Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'commPostLinks') && preg_match("~\<a(.*?)href\=(.*?)\>(.*?)\<\/a\>~i", $parsed)) {
							$err = true;
							Aurus::getInstance()->setError(__('Ви не можете залишати посилання на інші сайти'));
						}
						if (!$err) {
							Mysql::getInstance()->update('news_comments', array('text' => Mysql::getInstance()->escape($parsed)), 'com_id=' . $comId);
							Aurus::location(Url::formatUrl('news', array('shownews' => $com['news_id']), 1));
						}
					} else {
						$tpl->load('addcomments');
						$tpl->set('{editor}', Aurus::getInstance()->getEditor(Config::get('comEditor', 'news')));
						$tpl->set('{txt}', Parser::getInstance()->unParseBB(stripslashes($com['text'])));
						$tpl->deleteBlock('captcha');
						Aurus::getInstance()->addContent(Aurus::getInstance()->form_start() . $tpl->out() . '</form>');
					}
				}
			}
			return $ret;
		}
	}

	private function deleteComment($newsId, $commId) {
		Mysql::getInstance()->query("UPDATE `" . PREFIX . "_news` SET comm_num=comm_num-1 WHERE id=$newsId");
		Mysql::getInstance()->delete('news_comments', 'com_id=' . $commId);
	}

	public function ajaxConfirm($text, $comId, $auhorID) {
		$comInfo = Mysql::getInstance()->select('news_comments', '*', 'com_id=' . $comId);

		if (strlen($text) < Config::get('commMinLenght', 'news')) {
			return format(__('Коментар занадто короткий, збільшіть його хоча б до {%1%} символів'), Config::get('commMinLenght', 'news'));
		}
		if (!Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'commPostLinks') && preg_match("~\<a(.*?)href\=(.*?)\>(.*?)\<\/a\>~i", $parsed)) {
			return __('Ви не можете залишати посилання в коментарях');
		}


		if ((Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'commEditSelf') && $auhorID == $comInfo[0]['user_id']) || Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'commEditAll')) {
			$parsed = Parser::getInstance()->parse($text);
			Mysql::getInstance()->update('news_comments', array('text' => $parsed), 'com_id=' . $comId);
			return $parsed;
		} else {
			return __('Ви не можете редагувати цей коментар');
		}
	}

	public function initAdminArea() {
		switch ($_GET['todo']) {
			case 'moderate':
				define('MASS', false);
				include (dirname(__file__) . '/admin/mass.php');
				break;
			case 'mass':
				define('MASS', true);
				include (dirname(__file__) . '/admin/mass.php');
				break;
			case 'edit':
				include (dirname(__file__) . '/admin/edit.php');
				break;
			case 'main':
				include (dirname(__file__) . '/admin/main.php');
				break;
			case 'categories':
				include (dirname(__file__) . '/admin/categories.php');
				break;
			default: return;
			break;
		}
	}

	private function addNews() {

		Aurus::getInstance()->includeJs(LINK_ROOT . 'scripts/jquery_ajax_upload.js');
		Aurus::getInstance()->addJs("function upload(){
$.ajaxFileUpload({
url: '/index-ajax.php?module=news&upload_file=true',
secureuri:false,
fileElementId:'file',
dataType: 'html',
success: function (data, status)
{
$('#uploaded_list').html(data);
},
error: function (data, status, e)
{
$('#uploaded_list').html('" . __('Вибачте, сталась помилка - ') . "' + e);
}
});
}");
		$tpl = Template::getInstance();

		Aurus::getInstance()->setTitle(__('Додавання новини'));
		if (Users::getInstance()->is_logged()) {

			if (isset($_POST['category'])) {
				$err = false;
				$_POST = trimArray($_POST);
				if (empty($_POST['news_title'])) {
					Aurus::getInstance()->setError(__('Нозва новини не повинна бути порожня'));
					$err = true;
				}
				if (empty($_POST['news_short'])) {
					Aurus::getInstance()->setError(__('Короткий опис новини не повинен бути пустим'));
					$err = true;
				}
				if (!$err) {
					toInt($_POST['category']);
					Aurus::getInstance()->setError(__('Новина додана'));
					$AddNewstitle = $_POST['news_title'];
					$AddNewsshort = $_POST['news_short'];

					if (empty($_POST['news_full'])) {
						$AddNewsfull = $AddNewsshort;
					} else {
						$AddNewsfull = $_POST['news_full'];
					}

					$mtitle = Mysql::getInstance()->escape(htmlspecialchars($AddNewstitle));

					$mshort = Mysql::getInstance()->escape(Parser::getInstance()->parse($AddNewsshort));
					$mfull = Mysql::getInstance()->escape(Parser::getInstance()->parse($AddNewsfull));

					$is_moderated = (int) Users::getInstance()->getGroupData('addNewsNoModeration', Users::getInstance()->getLoggedUsersData('group'));

					Mysql::getInstance()->query("INSERT INTO " . PREFIX . "_news (title,sstory,fstory,author,category,comm_num,is_moderated,rating,is_fixed,time_add) VALUES ('{$mtitle}','{$mshort}','{$mfull}','" . Users::getInstance()->getLoggedUsersData('uid') . "','{$_POST['category']}','0','{$is_moderated}','0','','" . TIME . "')");
				}
			} else {
				$select = '<select name="category" style="width:200px">';
				$sa = $this->getArrayOfCategories();
				foreach ($sa as $id => $name) {
					$select .= '<option value="' . $id . '">' . stripslashes($name) . '</option>';
				}
				$select .= '</select>';

				$tpl = Template::getInstance();
				$tpl->load('addnews');

				$tpl->set('{tplTitle}', __('Додавання новини'));
				$tpl->set('{title}');
				$tpl->set('{category}', $select);
				$tpl->set('{editor}', Aurus::getInstance()->getEditor());
				$tpl->set('{short_story}');
				$tpl->set('{full_story}');
				$tpl->set('{upload}', '<input type="file" name="file" id="file" /><span class="news_upload" onclick="upload()">' . __('Завантажити') . '</span><div id="uploaded_list">' . $this->getUploaded() . '</div>');
				Aurus::getInstance()->addContent(Aurus::getInstance()->form_start('post', '', true) . $tpl->out() . '</form>');
			}
		} else {
			Aurus::getInstance()->setError(__('Незареєстровані користувачі не можуть додавати новини.Будь ласка, зареєструйтесь.'));
		}
	}

	private function showFull() {
		$id = explode('_', $_GET['shownews']);
		$id = toInt($id[0]);

		if ($id > 0) {
			//Adding comment
			if (isset($_POST['message']) && Config::get('commentsOn', 'news') && Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'addCommentsToNews')) {
				$this->addComment($id);
			}
			//End add comment
			
			////
			$getnews = Mysql::getInstance()->getarray("SELECT id,title,fstory,sstory,author,comm_num,category,time_add,is_fixed FROM `" . PREFIX . "_news` WHERE id='{$id}'");
			Aurus::getInstance()->setTitle(htmlspecialchars(stripslashes($getnews['title'])));

			Template::getInstance()->load('newsfull');
			Template::getInstance()->set('{news_title}', stripslashes($getnews['title']));
			Template::getInstance()->set('{full-story}', '<div id="newsId_' . $getnews['id'] . '">' . stripslashes($getnews['fstory']) . '</div>');
			Template::getInstance()->set('{author}', '<a href="' . Url::formatUrl('news', array('show' => 'user', 'id' => $getnews['author'])) . '">' . Users::getInstance()->getUserData('login', $getnews['author']) . '</a>');
			Template::getInstance()->set('{comm_num}', $getnews['comm_num']);
			Template::getInstance()->set('[full-link]', $this->formatHref($getnews['title'], $getnews['id']));
			Template::getInstance()->set('[/full-link]', '</a>');
			Template::getInstance()->set('{edit}', $this->getEditSelect($getnews['id'], $getnews['is_fixed']));
			Template::getInstance()->set('{link-category}', '<a href="' . Url::formatUrl('news', array('showcategory' => $getnews['category']), 1) . '">' . $this->getCatById($getnews['category']) . '</a>');
			Template::getInstance()->set('{date}', au_date(Config::get('timeformat', 'news'), $getnews['time_add']));


			if (Config::get('related', 'news')) {
				Template::getInstance()->set('{related}', $this->showRelated($id, addslashes(strip_tags($getnews['title'])), addslashes(strip_tags($getnews['fstory']))));
			} else {
				Template::getInstance()->set('{related}');
			}
			Aurus::getInstance()->setKeyWords(Aurus::getInstance()->createKeywords(stripslashes($getnews['fstory'])));
			Aurus::getInstance()->addContent(Template::getInstance()->out());
			Aurus::getInstance()->addContent($this->showComments($id));

			if (Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'addCommentsToNews')) {
				Aurus::getInstance()->addContent($this->addCommForm());
			}
		}
	}

	function showRelated($id, $title, $full) {
		if ($ret = Cache::get('related' . $id)) {
			return $ret;
		} else {
			$rel_m = Mysql::getInstance()->query("SELECT id, title FROM `" . PREFIX . "_news` WHERE MATCH (title, sstory, fstory)
				AGAINST ('" . $title . ' ' . $full . "')
				AND id != '$id'
				AND is_moderated='1'
				LIMIT 5");
			$related = '';
			if (mysql_num_rows($rel_m) > 0) {
				$related .= '<ul>';
				while ($m_rel = Mysql::getInstance()->fetch_assoc($rel_m)) {
					$related .= '<li><a href="' . Url::formatUrl('news', array('shownews' => $m_rel['id']), 1) . '">' . stripslashes($m_rel['title']) . '</a></li>';
				}
				$related .= '</ul>';
				Cache::set('related' . $id, $related);
				return $related;
			} else {
				return __('Схожих новин не знайдено');
			}
		}
	}

	private function showShort() {
		if (isset($_GET['showcategory']) && is_numeric($_GET['showcategory'])) {
			$cat = $_GET['showcategory'];
		} else {
			$cat = false;
		}
		if ($cat) {
			Aurus::getInstance()->setTitle($this->getCatById($cat));
			$and = 'AND category IN(' . $this->getCatChildren($cat) . ')';
		} else {
			$and = '';
		}

		$page = (isset($_GET['page']) && 0 < (int) $_GET['page']) ? $_GET['page'] : 1;

		$orderBy = Config::get('newsOrderBy', 'news');

		$ret = '';
		$perPage = Config::get('newsPerPage', 'news');
		$lStart = ($page - 1) * $perPage;

		$getnewsa = Factory::get("Mysql")->query("SELECT SQL_CALC_FOUND_ROWS * FROM " . PREFIX . "_news LEFT JOIN " . PREFIX . "_users ON author=uid WHERE is_moderated='1' $and ORDER BY is_fixed DESC, time_add $orderBy LIMIT $lStart,$perPage");

		$tpl = Factory::get("Template");
		while ($getnews = Factory::get("Mysql")->fetch_assoc($getnewsa)) {
			$tpl->load('newsshort');
			$tpl->set('[full-link]', $this->formatHref($getnews['title'], $getnews['id']));
			$tpl->set('[/full-link]', '</a>');
			$tpl->set('{news_title}', stripslashes($getnews['title']));
			$tpl->set('{short-story}', '<div id="newsId_' . $getnews['id'] . '">' . stripslashes($getnews['sstory']) . '</div>');
			$tpl->set('{author}', '<a href="' . Url::formatUrl('news', array('show' => 'user', 'id' => $getnews['uid'])) . '">' . $getnews['login'] . '</a>');
			$tpl->set('{edit}', $this->getEditSelect($getnews['id'], $getnews['is_fixed']));
			$tpl->set('{link-category}', '<a href="' . Url::formatUrl('news', array('showcategory' => $getnews['category']), 1) . '">' . $this->getCatById($getnews['category']) . '</a>');
			$tpl->set('{date}', au_date(Config::get('timeformat', 'news'), $getnews['time_add']));
			$tpl->set('{comm_num}', $getnews['comm_num']);
			$ret .= $tpl->out();
		}

		$news = Mysql::getInstance()->getarray("SELECT FOUND_ROWS() as count");
		$news = $news['count'];

		$ret .= Aurus::getInstance()->getPagesFromTemplate('news', (int) $news, $perPage, $page, array('show' => 'news'));
		Aurus::getInstance()->addContent($ret);
	}

	private function formatHref($title, $id) {
		$title = htmlspecialchars_decode(stripslashes(trim($title)));

		while (strpos($title, '  ') !== false) {
			$title = str_replace('  ', ' ', $title);
		}

		return '<a href="' . Url::formatUrl('news', array('shownews' => $id ), 1) . '">';
	}

	function getEditSelect($id, $fixed) {
		if (Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'editNews') or Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'deleteNews')) {
			$edit = '<select onchange="window.location=this.options[this.selectedIndex].value;this.selectedIndex=0"><option>' . __('Виберіть дію') . '</option>';
			if (Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'editNews')) {
				$edit .= '<option value="' . Url::formatUrl('news', array('edit' => 'news', 'id' => $id), 1) . '">' . __('Змінити') . '</option>';
			}
			if (Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'deleteNews')) {
				$edit .= '<option value="' . Url::formatUrl('news', array('delete' => 'news', 'id' => $id), 1) . '">' . __('Видалити') . '</option>';
			}
			if (Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'fixNews')) {
				if (boolean($fixed)) {
					$edit .= '<option value="' . Url::formatUrl('news', array('fix' => 'news', 'id' => $id), 1) . '">' . __('Зняти фіксацію') . '</option>';
				} else {
					$edit .= '<option value="' . Url::formatUrl('news', array('fix' => 'news', 'id' => $id), 1) . '">' . __('Зафіксувати') . '</option>';
				}
			}
			return $edit . '</select>';
		}
		return '';
	}

	function getCatById($id) {
		$catz = Cache::get('n_categories');
		if (!is_array($catz)) {
			$category = Mysql::getInstance()->query("SELECT * FROM " . PREFIX . "_categories");
			while ($cat = Mysql::getInstance()->fetch_assoc($category)) {
				$categoriess[] = array($cat['catid'], $cat['cat_name'], $cat['parent']);
			}
			Cache::set('n_categories', $categoriess);
			$catz = $categoriess;
		}
		foreach ($catz as $isd => $arr) {
			if ($arr[0] == $id) {
				return $arr[1];
			}
		}
	}

	function getCatChildren($id) {
		$catz = Cache::get('n_categories');
		if (!is_array($catz)) {
			$category = Mysql::getInstance()->query("SELECT * FROM " . PREFIX . "_categories");
			while ($cat = Mysql::getInstance()->fetch_assoc($category)) {
				$categoriess[] = array($cat['catid'], $cat['cat_name'], $cat['parent']);
			}
			Cache::set('n_categories', $categoriess);
			$catz = $categoriess;
		}
		if ($ret = Cache::get('cat_children_' . $id)) {
			return $ret;
		}
		/*
		[0] => id
		[1] => name
		[2] => parent
		*/
		$parents[] = $id;
		$ret[] = $id;

		while ($parent = array_shift($parents)) {
			foreach ($catz as $cat) {
				if ($cat[2] == $parent) {
					$parents[] = $cat[0];
					$ret[] = $cat[0];
				}
			}
		}
		return implode(',', $ret);
	}

	private function edit() {
		$tpl = Template::getInstance();

		$_GET['id'] = (int) $_GET['id'];
		if (isset($_GET['edit']) && $_GET['edit'] == 'comment') {
			$commentsClass->edit($_GET['id']);
		}

		if (isset($_GET['edit']) && $_GET['edit'] == 'news' && Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'editNews')) {
			if (isset($_POST['news_title'])) {
				$err = false;
				$_POST = trimArray($_POST);

				if (empty($_POST['news_title'])) {
					Aurus::getInstance()->setError(__('Назва новини не може бути порожньою'));
					$err = true;
				}
				if (empty($_POST['news_short'])) {
					Aurus::getInstance()->setError(__('Короткий опис новини не може бути порожній'));
					$err = true;
				}
				if (!$err) {
					Aurus::getInstance()->setError(__('Зміни збережено'));
					$AddNewstitle = $_POST['news_title'];
					$AddNewsshort = $_POST['news_short'];

					if (empty($_POST['news_full'])) {
						$AddNewsfull = $AddNewsshort;
					} else {
						$AddNewsfull = $_POST['news_full'];
					}

					Mysql::getInstance()->update('news', array(
					'title' => Mysql::getInstance()->escape(htmlspecialchars($_POST['news_title'])),
					'sstory' => Mysql::getInstance()->escape(Parser::getInstance()->parse($AddNewsshort)),
					'fstory' => Mysql::getInstance()->escape(Parser::getInstance()->parse($AddNewsfull)),),
					'id=' . $_GET['id']
					);
				}
			}

			$get = Mysql::getInstance()->getarray("SELECT * FROM `" . PREFIX . "_news` WHERE id='{$_GET['id']}' ");
			//debug($get);
			$select = '<select name="category" style="width:200px">';
			$sa = $this->getArrayOfCategories();
			foreach ($sa as $id => $name) {
				if ($id == $get['category']) {
					$select .= '<option selected="selected" value="' . $id . '">' . $name . '</option>';
				} else {
					$select .= '<option value="' . $id . '">' . $name . '</option>';
				}
			}
			$select .= '</select>';

			$tpl->load('addnews');
			$tpl->set('{tplTitle}', __('Редагування новини'));
			$tpl->set('{title}', stripslashes($get['title']));
			$tpl->set('{short_story}', Parser::getInstance()->unParseBB(stripslashes($get['sstory'])));
			$tpl->set('{full_story}', Parser::getInstance()->unParseBB(stripslashes($get['fstory'])));
			$tpl->set('{editor}', Aurus::getInstance()->getEditor());
			$tpl->set('{category}', $select);

			Aurus::getInstance()->setTitle(__('Редагування новини'));

			Aurus::getInstance()->addContent(Aurus::getInstance()->form_start() . $tpl->out() . '</form>');
		} elseif (isset($_GET['delete']) && $_GET['delete'] == 'news' && Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'deleteNews')) {
			if (isset($_GET['confirmDelete']) && $_GET['confirmDelete'] == 'yes') {
				Aurus::getInstance()->addContent(Aurus::getInstance()->setError(__('Новина видалена.')));
				Mysql::getInstance()->delete('news', 'id=' . $_GET['id']);
			} elseif (isset($_GET['confirmDismoderate']) && $_GET['confirmDismoderate'] == 'yes') {
				Aurus::getInstance()->addContent(Aurus::getInstance()->setError(__('Новина знята з модерації.')));
				Mysql::getInstance()->update('news', array('is_moderated' => '0'), 'id=' . $_GET['id']);
			} else {
				$buttons = '<input type="button" onclick="document.location.href=\'' . Url::formatUrl('news', array('delete' => 'news', 'id' => $_GET['id'], 'confirmDelete' => 'yes'), 1) . '\'" value="' . __('Видалити') . '"/> ';
				$buttons .= '<input type="button" onclick="document.location.href=\'' . Url::formatUrl('news', array('delete' => 'news', 'id' => $_GET['id'], 'confirmDismoderate' => 'yes'), 1) . '\'" value="' . __('Зняти з модерації') . '"/> ';
				$buttons .= '<input type="button" onclick="history.go(-1)" value="' . __('Відмінити') . '"/> ';
				Aurus::getInstance()->addContent(Aurus::getInstance()->setError(__('Видалити цю новину?') . '<br />' . $buttons));
			}
		}
	}

	public function getArrayOfCategories($p = 0, $sub = 0) {
		if (!Cache::exists('n_categories')) {
			$c = Cache::get('n_categories');
			$category = Mysql::getInstance()->query("SELECT * FROM " . PREFIX . "_categories");
			while ($cat = Mysql::getInstance()->fetch_assoc($category)) {
				$categoriess[] = array($cat['catid'], stripslashes($cat['cat_name']), $cat['parent']);
			}
			Cache::set('n_categories', $categoriess);
		}

		$all_cats = Cache::get('n_categories');
		$ret = array();

		if (count($all_cats)) {
			foreach ($all_cats as $cat) {
				$id = $cat[0];
				$name = $cat[1];
				$parent = $cat[2];

				if ($parent == $p) {
					$ret[$id] = str_repeat('-', $sub) . ' ' . $name;
					$ret += $this->getArrayOfCategories($id, $sub + 1);
				}
			}
		}
		return $ret;
	}

	//comments methods
	private function showComments($newsId) {
		$content = '';

		if (Config::get('commentsOn', 'news')) { //If comments are allowed
			if (isset($_GET['page']) && (int) $_GET['page']) {
				$comPage = toInt($_GET['page']);
			} else {
				$comPage = 1;
			}

			$startLim = ($comPage - 1) * Config::get('commentsCount', 'news');
			$comAra = Mysql::getInstance()->query("
			SELECT SQL_CALC_FOUND_ROWS *," . PREFIX . "_news_comments.email AS eml
			FROM " . PREFIX . "_news_comments
			LEFT JOIN " . PREFIX . "_users ON " . PREFIX . "_news_comments.user_id = " . PREFIX . "_users.uid
			WHERE " . PREFIX . "_news_comments.news_id='$newsId'
			ORDER BY com_id ASC
			LIMIT $startLim," . Config::get('commentsCount', 'news'));

			$kQ = false;

			while ($com = Mysql::getInstance()->fetch_assoc($comAra)) {
				$kQ = true;
				Template::getInstance()->load('comments');
				Template::getInstance()->set('{comment-id}', $com['com_id']);
				Template::getInstance()->set('{date}', au_date(Config::get('commTimeFormat', 'news'), $com['time']));
				Template::getInstance()->set('{comment}', '<div id="com-' . $com['com_id'] . '">' . stripslashes($com['text']) . '</div>');

				if ($com['is_logged']) { // Member wrote comment
					if ($com['signature']) {
						Template::getInstance()->set('{signature}', stripslashes($com['signature']));
						Template::getInstance()->set('[signature]');
						Template::getInstance()->set('[/signature]');
					} else {
						Template::getInstance()->deleteBlock('signature');
					}
					Template::getInstance()->set('{avatar}', $com['avatar'] ? LINK_ROOT . $com['avatar'] : Users::getInstance()->noavatar);
					Template::getInstance()->set('{group-name}', Users::getInstance()->getGroupData('groupname', $com['group']));
					Template::getInstance()->set('{author}', $com['login']);

					Template::getInstance()->set('[user-link]', '<a href="' . Url::formatUrl('news', array('show' => 'user', 'id' => $com['uid']), 1) . '">');
					Template::getInstance()->set('[/user-link]', '</a>');

					Template::getInstance()->setArrayTag('comment-data', $com);
				} else { // Guest wrote comment
					Template::getInstance()->deleteBlock('signature');
					Template::getInstance()->set('{avatar}', Users::getInstance()->noavatar);
					Template::getInstance()->set('{group-name}', Users::getInstance()->getGroupData('groupname', 4));
					Template::getInstance()->set('{author}', $com['user_name']);
					Template::getInstance()->pregSet("`\{user-data=[A-Za-z0-9_-]+\}`", '---');

					Template::getInstance()->set('[user-link]', Users::getInstance()->is_logged() ? '<a href="mailto:' . $com['eml'] . '">' : '');
					Template::getInstance()->set('[/user-link]', Users::getInstance()->is_logged() ? '</a>' : '');
				}

				if (Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'commEditSelf') || Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'commEditAll')) {
					Template::getInstance()->set('[edit-link]', '<a onclick="au_ajax(\'news\',{\'edit-com-id\':' . $com['com_id'] . '},\'com-' . $com['com_id'] . '\',1,0);return false;" href="' . Url::formatUrl('news', array('edit' => 'comment', 'id' => $com['com_id']), 1) . '">');
					Template::getInstance()->set('[/edit-link]', '</a>');
				} else {
					Template::getInstance()->deleteBlock('edit-link');
				}

				if (Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'commDeleteSelf') || Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'commDeleteAll')) {

					Template::getInstance()->set('[del-link]', '<a href="javascript:void(0)" onclick="if(confirm( \'' . __('Видалити коментар?') . '\' )){au_ajax(\'news\',\'del-com-id=' . $com['com_id'] . '\',\'com-' . $com['com_id'] . '\')}">');
					Template::getInstance()->set('[/del-link]', '</a>');
				} else {
					Template::getInstance()->deleteBlock('del-link');
				}

				$content .= Template::getInstance()->out();
			}
			if ($kQ) {
				$cnt = Mysql::getInstance()->getarray("SELECT FOUND_ROWS() as count");
				$cnt = $cnt['count'];
				$content .= Aurus::getInstance()->getPagesFromTemplate('news', $cnt, Config::get('commentsCount', 'news'), $comPage, array('shownews' => $newsId));
			}
			return $content;
		}
	}

	private function addCommForm() {
		$tpl = Template::getInstance();
		$tpl->load('addcomments');
		$tpl->set('{tplTitle}', __('Додати коментар'));
		$tpl->set('{editor}', Aurus::getInstance()->getEditor(Config::get('comEditor', 'news')));
		if (Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'), 'addCommCaptcha')) {
			$tpl->set('{captcha}', Modules::getInstance()->getCaptcha('news_addComment'));
			$tpl->set('[captcha]');
			$tpl->set('[/captcha]');
		} else {
			$tpl->deleteBlock('captcha');
		}
		$tpl->set('{txt}');
		return Aurus::getInstance()->form_start() . $tpl->out() . '</form>';
	}

	
	        function addComment($newsId){
                if (Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'),'addCommCaptcha')) {
                        if (!$modules->checkCaptcha($_POST['captcha'],'news_addComment')) {//Check if captcha code is valid
                                Aurus::getInstance()->setError(__('Код захисту введено з помилкою'));
                                return false;
                        }
                }
                if (strlen($_POST['message']) < (int) Config::get('commMinLenght','news')) {
                        Aurus::getInstance()->setError(format(__('Коментар занадто короткий, збільшіть його хоча б до {%1%} символів'),Config::get('commMinLenght','news')));
                        return false;
                }
                $parsed = Parser::getInstance()->parse($_POST['message']);
                if (!Users::getInstance()->can(Users::getInstance()->getLoggedUsersData('group'),'commPostLinks') && preg_match("~\<a(.*?)href\=(.*?)\>(.*?)\<\/a\>~i",$parsed)) {
                        Aurus::getInstance()->setError(__('Ви не можете додавати посилання на інші сайти'));
                        return false;
                }
                if (!Users::getInstance()->is_logged()) {
                        if (empty($_POST['name']) or (strlen($_POST['name']) < 4) ) {
                                Aurus::getInstance()->setError(__('Ваше ім\'я занадто коротке'));
                                return false;
                        }
                        if (empty($_POST['mail'])) {
                                Aurus::getInstance()->setError(__('Ви не ввели адресу Вашої електронної пошти'));
                                return false;
                        }
                        if (!$err && !isValidEmail($_POST['mail'])) {//Check email
                                Aurus::getInstance()->setError(__('Адреса Вашої електронної скриньки має невірний формат'));
                                return false;
                        }
                }
                //If function still works and not returned false
                $this->_addComment($newsId,$parsed);
        }

        private function _addComment($newsId,$parsed){
                $insertArray['news_id'] = $_GET['shownews'];
                $insertArray['user_id'] = Users::getInstance()->getLoggedUsersData('uid');
                $insertArray['time'] = TIME;
                $insertArray['text'] = $parsed;
                $insertArray['is_logged'] = Users::getInstance()->is_logged() ? '1' : '0';
                $insertArray['user_name'] = isset($_POST['name']) ? $_POST['name'] : '';
                $insertArray['email'] = isset($_POST['mail']) ? $_POST['mail'] : '';
                Mysql::getInstance()->insert('news_comments',$insertArray);
                Mysql::getInstance()->query("UPDATE `".PREFIX."_news` SET comm_num=comm_num+1 WHERE id='$newsId'");
                Mysql::getInstance()->query("UPDATE `".PREFIX."_users` SET com_count=com_count+1 WHERE uid='{$insertArray['user_id']}'");
                Aurus::location(Url::formatUrl(array('shownews' => $newsId),1));
        }

}